$(function() {
	// 页面控件
	var $dataTable = $('#dataTable'); // 表格
	var $dataTableToolbar = $('#dataTableToolbar'); // 表格：工具栏
	var $btnAddToggle = $('#btnAddToggle'); // 表格：添加按钮
	var $btnEditToggle = $('#btnEditToggle'); // 表格：修改按钮
	var $btnRemoveToggle = $('#btnRemoveToggle'); // 表格：删除按钮
	var $btnCheckAll = $('#btnCheckAll'); // 表格：全选按钮
	var $btnInvertCheck = $('#btnInvertCheck'); // 表格：反选按钮
	var $btnUncheckAll = $('#btnUncheckAll'); // 表格：取消选择按钮
	
	var $inputName = $('#inputName'); // 查询条件：名称
	var $inputIPBlock = $('#inputIPBlock'); // 查询条件：IP段
	var $chosenAreaList = $('#chosenAreaList'); // 查询条件：所属矿区
	var $chosenTypeList = $('#chosenTypeList'); // 查询条件：矿机类型
	var $chosenEnableList = $('#chosenEnableList'); // 查询条件：可用状态
	
	var $editDialog = $('#editDialog'); // 添加/修改窗口
	var $editDialogLabel = $('#editDialogLabel'); // 添加/修改窗口：标题
	var $editForm = $('#editForm'); // 添加/修改窗口：表单
	var $enable = $('#enable'); // 添加/修改窗口：：可用状态
	var $areaId = $('#areaId'); // 添加/修改窗口：“所属矿区”下拉列表框
	var $minerTypeId = $('#minerTypeId'); // 添加/修改窗口：“矿机类型”下拉列表框
	var $ipBeginning = $('#ipBeginning'); // 添加/修改窗口：起始IP索引
	var $ipEnd = $('#ipEnd'); // 添加/修改窗口：结束IP索引
	var $ignores = $('#ignores'); // 添加/修改窗口：“忽略的IP索引”下拉列表框
	var $areaIdTip = $('#areaIdTip'); // 添加/修改窗口：未选择所属矿区时的提示信息
	var $minerTypeIdTip = $('#minerTypeIdTip'); // 添加/修改窗口：未选择矿机类型时的提示信息
	var $btnSave = $('#btnSave'); // 添加/修改窗口：保存按钮
	var $btnReset = $('#btnReset'); // 添加/修改窗口：重置按钮
	
	var areasForTableEdit = [];
	var modelsForTableEdit = [];
	
	initAreaForTableEdit();
	
	function initAreaForTableEdit() {
		$.ajax({
			url: 'areas',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				if (result.success) {
					areasForTableEdit = [];
					var allDatas = result.rows;
					for (var i = 0; i < allDatas.length; i++) {
						var data = allDatas[i];
						areasForTableEdit.push({value:data.id, text:data.name});
					}
				}
				initModelForTableEdit();
			}
		});
	}
	
	function initModelForTableEdit() {
		$.ajax({
			url: 'types',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				if (result.success) {
					modelsForTableEdit = [];
					var allDatas = result.rows;
					for (var i = 0; i < allDatas.length; i++) {
						var data = allDatas[i];
						modelsForTableEdit.push({value:data.id, text:data.name});
					}
				}
				initWidgets();
				initListeners();
				initValidators();
			}
		});
	}
	
	
	var formData; // 表单数据
	var saveMode = 0; // 保存方式：1：添加；2：修改
	// 弹出添加窗口时使用的初始表单控件值
	var emptyData = {id:'', areaId:'', minerTypeId:'', name:'', ipBlock:'', ipBeginning:'', ipEnd:'', ignores:null, enable:true, remark:''};
	
	// 弹出添加窗口
	function openAddDialog() {
		$editDialogLabel.text('添加机架');
		initFormData(emptyData);
		$editDialog.modal('show');
		saveMode = 1;
	}

	// 弹出修改窗口
	function openEditDialog(data) {
		$editDialogLabel.text('修改机架');
		initFormData(data);
		$editDialog.modal('show');
		saveMode = 2;
	}

	// 弹出删除确认窗口
	function openRemoveDialog(datas) {
		var tableDatas = $dataTable.bootstrapTable('getData');
		var title = '';
		if (datas.length == 1) {
			title = '将删除机架' + datas[0].name + '。';
		} else if(datas.length == tableDatas.length) {
			title = '将删除所有机架。';
		} else {
			title = '将删除所选' + datas.length + '个机架。';
		}
		swal({
	        title: title,
	        type: "warning",
	        showCancelButton: true,
	        cancelButtonText : "让我再考虑一下…",
	        confirmButtonColor: "#ed5565",
	        confirmButtonText : "是的，我要删除！",
	        text: '删除操作无法恢复，请谨慎操作！'
	    }, function(isConfirm) {
			if (isConfirm) {
				doDelete(JSON.stringify(datas));
			}
		});
	}

	// 初始化表单控件的值
	function initFormData(data) {
		
		formData = data;
		$.each(formData, function (key, value) {
			$('#' + key).val(value);
		});
		if (data.enable == true) {
			$enable.prop('checked', true);
		} else {
			$enable.prop('checked', false);
		}
		initChosenAreaData(data.areaId);
		initChosenTypeData(data.minerTypeId);
		buildIgnoresChosen(data.ignores)
		$editForm.validate().form();
	}

	// 添加/修改窗口：根据IP起始和结束索引重建忽略的IP索引下拉列表框
	function buildIgnoresChosen(values) {
		var ipBeginning = $ipBeginning.val();
		var ipEnd = $ipEnd.val();
		if (!ipBeginning || !$.isNumeric(ipBeginning) || !ipEnd || !$.isNumeric(ipEnd)) {
			// IP起始和结束索引为空或非数字时置空忽略的IP索引下拉列表框
			$ignores.empty();
			$ignores.append($('<option value=""></option>'));
			$ignores.chosen('destroy').chosen({width:'100%'});
			return;
		}
		
		ipBeginning = parseInt(ipBeginning);
		ipEnd = parseInt(ipEnd);
		
		// IP索引需在1-254之间，且起始索引不能大于结束索引
		if (ipBeginning < 0) {
			ipBeginning = 0;
			$ipBeginning.val(ipBeginning);
		}
		if (ipBeginning > 255) {
			ipBeginning = 255;
			$ipBeginning.val(ipBeginning);
		}
		if (ipEnd < 0) {
			ipEnd = 0;
			$ipEnd.val(ipEnd);
		}
		if (ipEnd > 255) {
			ipEnd = 255;
			$ipEnd.val(ipEnd);
		}
		if (ipBeginning > ipEnd) {
			var temp = ipBeginning;
			ipBeginning = ipEnd;
			ipEnd = temp;
			$ipBeginning.val(ipBeginning);
			$ipEnd.val(ipEnd);
		}
		
		// 当IP起始索引或结束索引发生改变时，检查“忽略的IP索引”下拉列表框中的值，若存在索引范围之外的值则去除
		if (!values) {
			var selections = $ignores.val();
			values = new Array();
			if (selections) {
				if ($.isArray(selections)) {
					for (var i = 0; i < selections.length; i++) {
						if (selections[i] >= ipBeginning && selections[i] <= ipEnd) {
							values[i] = selections[i];
						}
					}
				} else {
					if (selections >= ipBeginning && selections <= ipEnd) {
						values[0] = selections;
					}
				}
			}
		}
		
		// 重建“忽略的IP索引”下拉框
		$ignores.empty();
		$ignores.append($('<option value=""></option>'));
		for (var i = ipBeginning; i <= ipEnd; i++) {
			$ignores.append($('<option></option>').val(i).html(i));
		}
		$ignores.val(values);
		$ignores.chosen('destroy').chosen({width:'100%'});
	}

	// 重置表单
	function doReset() {
		initFormData(formData);
	}

	// 保存（修改或添加）
	function doSave() {
		var data = $editForm.serializeObject();
		if (data.enable) {
			data.enable = true;
		} else {
			data.enable = false;
		}
		if (data.ignores && !$.isArray(data.ignores)) {
			var arr = new Array();
			arr[0] = data.ignores;
			data.ignores = arr;
		} else {
			data.ignores = null;
		}
		var paramData = JSON.stringify(data);
		if (saveMode == 1) {
			doPost(paramData);
		} else if (saveMode == 2) {
			doPut(paramData, true);
		}
	}

	// 添加
	function doPost(data) {
		$.ajax({
			url: 'shelfs',
			type: 'POST',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '添加成功');
					$editDialog.modal('hide');
					$dataTable.bootstrapTable('refresh');
				} else {
					toastr.error(result.message, '添加失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
			}
		});
	}

	// 修改
	function doPut(data, refresh) {
		$.ajax({
			url: 'shelfs',
			type: 'PUT',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '修改成功');
					$editDialog.modal('hide');
				} else {
					toastr.error(result.message, '修改失败');
				}
				if (refresh) {
					$dataTable.bootstrapTable('refresh');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
				if (refresh) {
					$dataTable.bootstrapTable('refresh');
				}
			}
		});
	}

	// 删除
	function doDelete(data) {
		$.ajax({
			url: 'shelfs',
			type: 'DELETE',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '删除成功');
					$dataTable.bootstrapTable('refresh');
				} else {
					toastr.error(result.message, '删除失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
			}
		});
	}

	function getHeight() {
	    return $(window).height() - 40;
	}

	// 初始化表单验证
	function initValidators() {
		var validIcon = "<i class='fa fa-times-circle'></i> ";
		$editForm.validate({
			rules: {
				name: { required: true, minlength: 2, maxlength: 80 },
				ipBlock: { required: true, ipBlock: true },
				ipBeginning: {required: true, digits:true, min: 0, max:255},
				ipEnd: {required: true, digits:true, min: 0, max:255},
				remark: { required: false, maxlength: 300 }
			},
			messages: {
				name: validIcon + '矿区名称须为2-80个字符。',
				remark: validIcon + '备注不能超过300个字符。',
				ipBlock: '请输入正确的IP段，如192.168.10。',
				ipBeginning: 'IP起始索引必须为0-255的整数。',
				ipEnd: 'IP结束索引必须为0-255的整数。'
			}
		});
	}

	// 初始化事件监听
	function initListeners() {
		$(window).resize(function () {
			$dataTable.bootstrapTable('resetView', {
	            height: getHeight()
	        });
	    });
		
		// 查询条件：“所属矿区”下拉列表-值改变时刷新数据表格
		$chosenAreaList.on('change', function() {
			$dataTable.bootstrapTable('refresh');
		});
		// 查询条件：“矿机类型”下拉列表框-值改变时刷新数据表格
		$chosenTypeList.on('change', function() {
			$dataTable.bootstrapTable('refresh');
		});
		// 查询条件：名称-值改变时刷新数据表格
		$inputName.on('change', function() {
			$dataTable.bootstrapTable('refresh');
		});
		// 查询条件：IP段-值改变时刷新数据表格
		$inputIPBlock.on('change', function() {
			$dataTable.bootstrapTable('refresh');
		});
		// 查询条件：“可用状态”下拉列表框-值改变时刷新数据表格
		$chosenEnableList.on('change', function() {
			$dataTable.bootstrapTable('refresh');
		});
		
		// 添加/修改窗口：“所属矿区”下拉列表框-值改变时显示或隐藏提示信息
		$areaId.on('change', function() {
			if (!$areaId.val()) {
				$areaIdTip.show();
			} else {
				$areaIdTip.hide();
			}
		});
		// 添加/修改窗口：“矿机类型”下拉列表框-值改变时显示或隐藏提示信息
		$minerTypeId.on('change', function() {
			if (!$minerTypeId.val()) {
				$minerTypeIdTip.show();
			} else {
				$minerTypeIdTip.hide();
			}
		});
		// 添加/修改窗口：起始IP索引-值改变时重建“忽略的IP索引”下拉列表框
		$ipBeginning.on('change', function() {
			buildIgnoresChosen();
		});
		// 添加/修改窗口：结束IP索引-值改变时重建“忽略的IP索引”下拉列表框
		$ipEnd.on('change', function() {
			buildIgnoresChosen();
		});
		// 添加/修改窗口：保存按钮
		$btnSave.on('click', function() {
			var valid = $editForm.validate().form();
			if (!$areaId.val()) {
				valid &= false;
				$areaIdTip.show();
			} else {
				$areaIdTip.hide();
			}
			if (!$minerTypeId.val()) {
				valid &= false;
				$minerTypeIdTip.show();
			}else {
				$minerTypeIdTip.hide();
			}
			if (!valid) {
				return;
			}
			doSave();
		});
		// 添加/修改窗口：重置按钮
		$btnReset.on('click', function() {
			doReset();
		});
		
		// 表格：添加按钮
		$btnAddToggle.on('click', function() {
			openAddDialog();
		});
		// 表格：修改按钮
		$btnEditToggle.on('click', function() {
			var selections = $dataTable.bootstrapTable('getSelections');
			if (selections.length == 0) {
				toastr.warning('请选择一个要修改的机架。', '提示');
				return;
			} else if (selections.length > 1) {
				toastr.warning('只能选择一个机架进行修改。', '提示');
				return;
			}
			openEditDialog(selections[0]);
		});
		// 表格：删除按钮
		$btnRemoveToggle.on('click', function() {
			var selections = $dataTable.bootstrapTable('getSelections');
			if (selections.length == 0) {
				toastr.warning('请选择要删除的机架。', '提示');
				return;
			}
			openRemoveDialog(selections);
		});
		// 表格：全选按钮
		$btnCheckAll.on('click', function() {
			$dataTable.bootstrapTable('checkAll');
		});
		// 表格：反选按钮
		$btnInvertCheck.on('click', function() {
			var datas = $dataTable.bootstrapTable('getData');
			for (var i=0; i<datas.length; i++) {
				if (datas[i].checkStatus) {
					$dataTable.bootstrapTable('uncheck', i);
				} else {
					$dataTable.bootstrapTable('check', i);
				}
			}
		});
		// 表格：取消选择按钮
		$btnUncheckAll.on('click', function() {
			$dataTable.bootstrapTable('uncheckAll');
		});
	}

	// 查询条件 和 添加/修改窗口 中的 “所属矿区”下拉列表-添加数据
	function initChosenAreaData(selection) {
		$.ajax({
			url: 'areas',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				if (result.success) {
					areasForTableEdit = [];
					$chosenAreaList.empty();
					$areaId.empty();
					$chosenAreaList.append($('<option></option>').val('').html(''));
					$areaId.append($('<option></option>').val('').html(''));
					var allDatas = result.rows;
					for (var i = 0; i < allDatas.length; i++) {
						var data = allDatas[i];
						$chosenAreaList.append($('<option></option>').val(data.id).html(data.name));
						$areaId.append($('<option></option>').val(data.id).html(data.name));
						areasForTableEdit.push({id:data.id, text:data.name});
					}
					$areaId.val(selection);
					$chosenAreaList.chosen('destroy').chosen({allow_single_deselect: true, width:'150px'});
					$areaId.chosen('destroy').chosen({allow_single_deselect: true, width:'100%'});
				} else {
					toastr.error(result.message, '矿区下拉列表数据获取失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '矿区下拉列表数据获取失败');
			}
		});
	}
	
	// 查询条件 和 添加/修改窗口 中的 “矿机类型”下拉列表框-添加数据
	function initChosenTypeData(selection) {
		$.ajax({
			url: 'types',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				if (result.success) {
					modelsForTableEdit = [];
					$chosenTypeList.empty();
					$minerTypeId.empty();
					$chosenTypeList.append($('<option></option>').val('').html(''));
					$minerTypeId.append($('<option></option>').val('').html(''));
					var allDatas = result.rows;
					for (var i = 0; i < allDatas.length; i++) {
						var data = allDatas[i];
						$chosenTypeList.append($('<option></option>').val(data.id).html(data.name));
						$minerTypeId.append($('<option></option>').val(data.id).html(data.name));
						modelsForTableEdit.push({id:data.id, text:data.name});
					}
					$minerTypeId.val(selection);
					$chosenTypeList.chosen('destroy').chosen({allow_single_deselect: true, width:'100px'});
					$minerTypeId.chosen('destroy').chosen({allow_single_deselect: true, width:'100%'});
				} else {
					toastr.error(result.message, '矿机类型下拉列表数据获取失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '矿机类型下拉列表数据获取失败');
			}
		});
	}
	
	// 初始化页面控件
	function initWidgets() {
		// 添加/修改窗口：“忽略的IP索引”下拉列表框-初始化
		$ignores.chosen({width:'100%'});
		// 查询条件：“所属矿区”下拉列表-初始化
		$chosenAreaList.chosen({allow_single_deselect: true, width:'150px'});
		// 添加/修改窗口：“所属矿区”下拉列表
		$areaId.chosen({allow_single_deselect: true, width:'100%'});
		// 查询条件 和 添加/修改窗口 中的 “所属矿区”下拉列表-添加数据
		initChosenAreaData('');
		// 查询条件：“矿机类型”下拉列表框-初始化
		$chosenTypeList.chosen({allow_single_deselect: true, width:'100px'});
		// 添加/修改窗口：“矿机类型”下拉列表框-初始化
		$minerTypeId.chosen({allow_single_deselect: true, width:'100%'});
		// 查询条件 和 添加/修改窗口 中的 “矿机类型”下拉列表框-添加数据
		initChosenTypeData('');
		// 查询条件：“可用状态”下拉列表框
		$chosenEnableList.chosen({allow_single_deselect: true, width:'80px'});
		
		// 表格
		$dataTable.bootstrapTable({
			height: getHeight(),
			url: 'shelfs',
			queryParams: function(params) { // 构建表格查询参数
				var areaId = $chosenAreaList.val();
				var minerTypeId = $chosenTypeList.val();
				var name = $inputName.val();
				var ipBlock = $inputIPBlock.val();
				var enable = null;
				var enableVal = $chosenEnableList.val();
				if (enableVal == '1') {
					enable = true;
				} else if (enableVal == '-1') {
					enable = false;
				} else {
					enable = null;
				}
				var params = {
								areaId: areaId,
								minerTypeId: minerTypeId,
								name: name,
								ipBlock: ipBlock,
								enable: enable,
								sort: params.sort,
								order: params.order
							};
				return params;
			},
			idField: 'id',
			//clickToSelect: true,
			pagination: false,
			sidePagination: 'server',
			showRefresh: true,
			showToggle: true,
			showColumns: true,
			toolbar: '#dataTableToolbar',
			iconSize: 'outline',
			icons: {
				paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
	            paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
	            refresh: 'glyphicon-repeat',
				toggle: 'glyphicon-list-alt',
				columns: 'glyphicon-list',
	            detailOpen: 'glyphicon-plus icon-plus',
	            detailClose: 'glyphicon-minus icon-minus'
			},
			editable: true,
			onEditableSave: function(field, row, oldValue, $el) {
				doPut(JSON.stringify(row), false);
			},
			rowStyle: function(row, index) { // 机架所属矿区不可用时高亮显示整行
				if (row.areaEnable == false) {
					return {classes: 'warning'};
				}
				return {};
			},
			columns: [
				{
					field: 'checkStatus',
					checkbox: true,
					align: 'center'
				},
				{
					field: 'id',
					title: 'ID',
					align: 'center',
					sortable: true,
					visible: false
				},
				{
//					field: 'areaName',
					field: 'areaId',
					title: '所属矿区',
					halign: 'center',
					align: 'left',
					editable: {
						type: 'select',
						source: areasForTableEdit
					}
				},
				{
					field: 'name',
					title: '机架名称',
					halign: 'center',
					align: 'left',
					sortable: true,
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							if (!value || value.length < 2 || value.length > 80) {
								return '机架名称必须为2-80个字符。';
							}
							return '';
						}
					}
				},
				{
					//field: 'minerTypeName',
					field: 'minerTypeId',
					title: '矿机类型',
					halign: 'center',
					align: 'left',
					editable: {
						type: 'select',
						source: modelsForTableEdit
					}
				},
				{
					field: 'ipBlock',
					title: 'IP段',
					halign: 'center',
					align: 'left',
					sortable: true,
				},
				{
					field: 'ipBeginning',
					title: 'IP起始索引',
					halign: 'center',
					align: 'right',
				},
				{
					field: 'ipEnd',
					title: 'IP结束索引',
					halign: 'center',
					align: 'right',
				},
				{
					field: 'ignores',
					title: '忽略的IP索引',
					halign: 'center',
					align: 'right',
					formatter: function(value, row, index) {
						if (!value) {
							return value;
						}
						return '<button class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="' + value + '">' + value.length + '个</button>'
					}
				},
				{
					field: 'minerCount',
					title: '矿机数量',
					align: 'center',
					align: 'right',
					formatter: function(value, row, index) {
						var end = row.ipEnd ? row.ipEnd : 0;
						var beginng = row.ipBeginning ? row.ipBeginning : 0;
						var ignore = row.ignores ? row.ignores.length : 0;
						return end - beginng + 1 - ignore;
					}
				},
				{
					field: 'enable',
					title: '可用状态',
					align: 'center',
					sortable: true,
					sortName: 'enable',
					formatter: function(value, row, index) {
						var icon = value == true ? '<img src="../img/icon/icon-enabled.png" width="20" height="20" />' : '<img src="../img/icon/icon-disabled.png" width="20" height="20" />';
						var btn = value == true ? '<a class="disable" href="javascript:void(0)">禁用</a>' : '<a class="enable" href="javascript:void(0)">启用</a>';
						return icon + ' ' + btn;
					},
					events: window.operateEvents = {
							'click .enable': function (e, value, row, index) {
								row.enable = true;
								doPut(JSON.stringify(row), false);
								$dataTable.bootstrapTable('updateRow', {index:index, row:row});
					        },
					        'click .disable': function (e, value, row, index) {
					        	row.enable = false;
								doPut(JSON.stringify(row), false);
								$dataTable.bootstrapTable('updateRow', {index:index, row:row});
					        }
					}
				},
				{
					field: 'remark',
					title: '备注',
					halign: 'center',
					align: 'left',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							if (!value && value.length > 300) {
								return '备注不能超过300个字符。';
							}
							return '';
						}
					}
				},
				{
					field: 'operate',
					title: '操作',
					align: 'center',
					events: window.operateEvents = {
							'click .edit': function (e, value, row, index) {
								openEditDialog(row);
					        },
					        'click .delete': function (e, value, row, index) {
					        	var rows = new Array(1);
					        	rows[0] = row;
					        	openRemoveDialog(rows);
					        }
					},
					formatter: function(value, row, index) {
						return [
								'<a class="edit" href="javascript:void(0)" title="修改">',
								'<i class="glyphicon glyphicon-edit"></i>',
								'</a>  ',
								'<a class="delete" href="javascript:void(0)" title="删除">',
								'<i class="glyphicon glyphicon-remove"></i>',
								'</a>'
						       ].join('');
					}
				}
			]
		});
	}
	
});